package com.cet.juc;

import java.util.concurrent.*;

public class CompletableFutureDemo {
    public static void main(String[] args) {
        final ExecutorService threadPool = Executors.newFixedThreadPool(1);
        try {
            final CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
                System.out.println(Thread.currentThread().getName() + "\t -----------come in");
                int result = ThreadLocalRandom.current().nextInt(10);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("获得的值为：" + result);
                if (result > 4) {
                    int i = 10 /0;
                }
                return result;
            }, threadPool).whenComplete((v,e) -> {
                if (e == null) {
                    System.out.println("已成功做了一系列操作！最终的值为：" + v);
                }
            }).exceptionally( e -> {
                e.printStackTrace();
                System.out.println("发生异常，异常产因为：" + e.getCause() + "\t" + e.getMessage());
                return null;
            });
        }finally {
            threadPool.shutdown();
        }

        System.out.println(Thread.currentThread().getName() + "正在执行一些其他任务！");

    }
}
